package com.ktjy.car.service.impl;

import com.ktjy.car.entity.Brand;
import com.ktjy.car.mapper.BrandMapper;
import com.ktjy.car.service.BrandService;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class BrandServiceImpl implements BrandService {

    @Resource
    private BrandMapper brandMapper;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    private static final String BRAND_LIST_KEY = "brand:list";
    private static final long CACHE_TIMEOUT = 24; // 缓存24小时

    @Override
    public List<Brand> selectAll() {
        return brandMapper.selectAll();
    }

    @Override
    public List<Brand> getFromCache() {
        // 尝试从Redis获取
        Object cachedBrands = redisTemplate.opsForValue().get(BRAND_LIST_KEY);
        
        if (cachedBrands != null) {
            if (cachedBrands instanceof List) {
                List<?> list = (List<?>) cachedBrands;
                if (!list.isEmpty() && list.get(0) instanceof Brand) {
                    return (List<Brand>) list;
                }
            }
            // 如果缓存数据格式不正确，删除缓存
            redisTemplate.delete(BRAND_LIST_KEY);
        }

        // 如果缓存中没有或数据格式不正确，从数据库获取
        List<Brand> brands = selectAll();
        
        // 存入Redis缓存
        if (brands != null && !brands.isEmpty()) {
            redisTemplate.opsForValue().set(BRAND_LIST_KEY, brands, CACHE_TIMEOUT, TimeUnit.HOURS);
        }

        return brands;
    }
}